functions in C Program

06-11-17 Course- C

The function in C language is also known as procedure or subroutine in other programming languages.

To do any work, we can create functions. A function can be said multiple times, it provides modularity and code reusable.

Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.

Syntax to declare function in C

The syntax of creating function in c language is given below:


return_type function_name(data_type parameter...){   //code to be executed   }  

Syntax to call function in C

The syntax of calling function in c language is given below:


variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.

Example of function in C

Let's see the simple program of function in c language.


#include <stdio.h>      
#include <conio.h>    
//defining function    
int cube(int n){  
return n*n*n;  
}  
void main(){      
int result1=0,result2=0;    
clrscr();      
  
result1=cube(2);//calling function  
result2=cube(3);    
      
printf("%d \n",result1);  
printf("%d \n",result2);  
  
getch();      
}      

Output


8
27